<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>语音识别</title>
  <style>

    #uploadflieContainer  {
      width: 600px;
      margin: 0 auto;
    }

    #mask{
      width: 600px;
      background: rgba(0,0,0,0.05);
      /*padding: 3rem 0 1rem 0;*/
      /*display: none;*/
      margin: 0 auto;
      /*margin-top: 51%;*/
    }

    #mask p{
      text-align: center;
      font-size: 20px;
      color: rgba(0,0,0,0.5);
    }

    img{
      display: block;
      width:40%;
      margin: 0 auto;
    }

    .start{
      width: 600px;
      margin: 0 auto;
      text-align: center;
    }

    #start{
      background-color: aqua;
      width: 100px;
      height: 30px;
    }

    #yuyin{
      width: 600px;
      margin: 30px auto;
      text-align: center;
    }

    #audio-container {
      width: 600px;
      margin: 0 auto;
      text-align: center;
    }

    audio {
      display: block;
      margin: 0 auto 10px;
    }

    .result{
      width: 600px;
      margin: 0 auto;
      text-align: center;
    }

    textarea{
      width: 400px;
      height: 300px;
    }
  </style>
</head>
<body>

<div id="mask">
  <img th:src="@{/img/a.jpg}" alt="">
  <p id="tip">点击按钮开始录音</p>
</div>
<div class="start">
  <button id="start" class="ui-btn ui-btn-primary">开始</button>
</div>

<div id="uploadflieContainer" >
  上传语音：<input type="file" id="uploadflie" accept="audio/mp3 ,audio/m4a,audio/wav,audio/pcm">
</div>


<div id="yuyin">
  语音内容：<div id="audio-container"></div>
</div>


<div class="result">
  识别结果：<textarea id="result"></textarea>
</div>



<script th:src="@{/js/axios.js}"></script>
<script th:src="@{/js/lame.min.js}"></script>

<script>

  var fileUpload = document.getElementById('uploadflie');

  var result = document.getElementById('result');

  fileUpload.onchange = function () {


    var file = this.files;

    console.log(file);

    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function () {

      let newData = reader.result.replace(/^data:audio\/\w+;base64,/, '') // replace + 正则 把前缀替换成空

      axios({
        // 请求方法
        method: 'GET',
        url: '/test5',
        // url参数
        params: {
          myData: newData,
          // size: file[0].size
        }
      }).then(function (response) {
        console.log(response.data);
        let string = response.data;
        var textArea = document.getElementById('result');
        // 处理成功情况
        textArea.innerHTML = string;
      });
    };
  }
</script>

<script>

  var container = document.querySelector('#audio-container');
  var mask = document.getElementById('mask');
  var start = document.querySelector('#start');
  var tip = document.getElementById('tip');
  var flag = true;


  if (navigator.mediaDevices.getUserMedia) {

    /*获取浏览器的录音权限，contraint是需要获取权限的列表*/
    const constraints = { audio: true };

    //返回的是Promise对象，因为需要等到用户确定授予权限的时候，
    // 我们才会处理下面的步骤,navigator是浏览器对象，
    // 我们就是通过navigator获取录音权限,成功回调的话就会获取到一个stream，
    // 然后将这个stream放入到我们下面创建的录音实例里面去
    navigator.mediaDevices.getUserMedia(constraints).then(
            stream => {
              console.log("授权成功！");
              var chunks = [];



              var types = ["video/webm",
                "audio/webm",
                "video/webm\;codecs=vp8",
                "video/webm\;codecs=daala",
                "video/webm\;codecs=h264",
                "audio/webm\;codecs=opus",
                      'audio/mpeg',
                      'aduio/pcm',
                "video/mpeg"];

              var options = {
                audioBitsPerSecond : 16000,
                mimeType: 'audio/webm'
              }

              for (var i in types) {
                console.log( "Is " + types[i] + " supported? " + (MediaRecorder.isTypeSupported(types[i]) ? "Maybe!" : "Nope :("));
              }

              //通过该方法创建录音实例
              const mediaRecorder = new MediaRecorder(stream,options);




              start.addEventListener('click',function(){

                if (mediaRecorder.state === "recording") {
                  mediaRecorder.stop();
                  console.log(chunks)
                  mediaRecorder.onstop = e => {
                    var blob = new Blob(chunks, { type: 'audio/webm' });
                    chunks = [];

                    // 获取 数据(Blob)
                    var audio = document.createElement('audio');
                    console.log(blob);
                    audio.src = URL.createObjectURL(blob);
                    audio.controls = true;
                    container.appendChild(audio);






                    const fileReader = new FileReader();
                    fileReader.onload = (e) => {
                      console.log(e);
                      this.mp3Base64 = e.target.result;
                      console.log(this.mp3Base64);
                      let newData1 = this.mp3Base64.replace(/^data:audio\/\w+;base64,/, '') // replace + 正则 把前缀替换成空
                      axios({
                        // 请求方法
                        method: 'GET',
                        url: '/test5',
                        // url参数
                        params: {
                          myData: newData1,
                          // dataSize: size
                        }
                      }).then(function (response) {
                        console.log(response.data);

                        let string = response.data;
                        var textArea = document.getElementById('result');
                        // 处理成功情况
                        textArea.innerHTML = string;
                      });

                    };

                    fileReader.readAsDataURL(blob);

                    // fileReader.readAsArrayBuffer(blob);

                    tip.innerText="点击按钮开始录音";
                    start.innerHTML="开始";
                    clearTimeout(timer);

                  };
                } else {
                  mediaRecorder.start();
                  mediaRecorder.ondataavailable = function(e) {
                    chunks.push(e.data);
                  };

                  // 开始录音
                  tip.innerText="正在录音";
                  timer = setTimeout(function(){
                    var audio = document.querySelectorAll('audio');
                    for(var i = 0; i < audio.length; i++){
                      if(!audio[i].paused){
                        audio[i].pause();
                      }
                    }
                  },500);
                  start.innerHTML="再次点击结束";
                }
                console.log("录音器状态：", mediaRecorder.state);
              });
            },
            () => {
              console.error("授权失败！");
            }
    );
  } else {
    console.error("浏览器不支持 getUserMedia");
  }

</script>
</body>
</html>